package com.example.app.ui.settings;

import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.example.app.MainActivity;
import com.example.app.R;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.slider.Slider;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.util.zip.CRC32;

public class SettingsFragment extends Fragment {
    private static final String PREF_NAME = "AppSettings";
    private static final String KEY_XUNFEI_APP_ID = "xunfei_app_id";
    private static final String KEY_XUNFEI_API_SECRET = "xunfei_api_secret";
    private static final String KEY_XUNFEI_API_KEY = "xunfei_api_key";
    private static final String KEY_DEEPSEEK_API_KEY = "deepseek_api_key";
    private static final String KEY_DPI_STEP = "dpi_step";
    private static final String TAG = "SettingsFragment";

    private EditText xunfeiAppIdInput;
    private EditText xunfeiApiSecretInput;
    private EditText xunfeiApiKeyInput;
    private EditText deepseekApiKeyInput;
    private Slider dpiSlider;
    private TextView dpiValueText;
    private TextView currentDpiText;
    private TextView firmwareVersionText;
    private SharedPreferences sharedPreferences;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_settings, container, false);

        // 初始化SharedPreferences
        sharedPreferences = requireContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);

        // 初始化输入框
        xunfeiAppIdInput = view.findViewById(R.id.xunfei_app_id_input);
        xunfeiApiSecretInput = view.findViewById(R.id.xunfei_api_secret_input);
        xunfeiApiKeyInput = view.findViewById(R.id.xunfei_api_key_input);
        deepseekApiKeyInput = view.findViewById(R.id.deepseek_api_key_input);
        dpiSlider = view.findViewById(R.id.dpi_slider);
        dpiValueText = view.findViewById(R.id.dpi_value);
        currentDpiText = view.findViewById(R.id.current_dpi);
        firmwareVersionText = view.findViewById(R.id.firmware_version);

        // 设置DPI滑块范围
        dpiSlider.setValueFrom(2);  // 最小步进值为2
        dpiSlider.setValueTo(116);  // 最大步进值为116
        dpiSlider.setStepSize(1);

        // 设置输入框属性
        setupEditTexts();

        // 加载保存的值
        loadSavedValues();

        // 设置保存按钮点击事件
        view.findViewById(R.id.btn_save_settings).setOnClickListener(v -> saveSettings());

        // 显示版本信息
        TextView versionInfo = view.findViewById(R.id.version_info);
        try {
            String versionName = requireContext().getPackageManager()
                    .getPackageInfo(requireContext().getPackageName(), 0).versionName;
            versionInfo.setText("版本 " + versionName);
        } catch (PackageManager.NameNotFoundException e) {
            versionInfo.setText("版本信息获取失败");
        }

        // 添加DPI滑动监听
        dpiSlider.addOnChangeListener((slider, value, fromUser) -> {
            int step = (int) value;
            int dpi = (int)(step * 27.8);
            dpiValueText.setText(String.format("DPI: %d", dpi));
        });

        // 更新当前DPI值
        updateCurrentDpi();

        // 更新固件版本
        updateFirmwareVersion();

        return view;
    }

    private void setupEditTexts() {
        // 设置所有输入框为单行模式
        xunfeiAppIdInput.setSingleLine(true);
        xunfeiApiSecretInput.setSingleLine(true);
        xunfeiApiKeyInput.setSingleLine(true);
        deepseekApiKeyInput.setSingleLine(true);

        // 设置输入类型为文本
        xunfeiAppIdInput.setInputType(android.text.InputType.TYPE_CLASS_TEXT);
        xunfeiApiSecretInput.setInputType(android.text.InputType.TYPE_CLASS_TEXT);
        xunfeiApiKeyInput.setInputType(android.text.InputType.TYPE_CLASS_TEXT);
        deepseekApiKeyInput.setInputType(android.text.InputType.TYPE_CLASS_TEXT);

        // 设置提示文本
        xunfeiAppIdInput.setHint("APPID");
        xunfeiApiSecretInput.setHint("APISecret");
        xunfeiApiKeyInput.setHint("APIKey");
        deepseekApiKeyInput.setHint("API Key");
    }

    private void loadSavedValues() {
        // 从SharedPreferences加载保存的值，如果没有则使用默认值
        xunfeiAppIdInput.setText(sharedPreferences.getString(KEY_XUNFEI_APP_ID, "f62d17ec"));
        xunfeiApiSecretInput.setText(sharedPreferences.getString(KEY_XUNFEI_API_SECRET, "NzJmMzg2MmRiZDJmNDIiNZA3ZGM1NiM4"));
        xunfeiApiKeyInput.setText(sharedPreferences.getString(KEY_XUNFEI_API_KEY, "3b40bc3bc25a0a3b1e0c0cc85558c6a1"));
        deepseekApiKeyInput.setText(sharedPreferences.getString(KEY_DEEPSEEK_API_KEY, "sk-db6fcca7e65649a6bbc05f55057707aa"));
        
        // 加载DPI步进值
        String savedDpiStep = sharedPreferences.getString(KEY_DPI_STEP, "2");
        try {
            float dpiStep = Float.parseFloat(savedDpiStep);
            if (dpiStep < 2) dpiStep = 2;
            if (dpiStep > 116) dpiStep = 116;
            dpiSlider.setValue(dpiStep);
            int dpi = (int)(dpiStep * 27.8);
            dpiValueText.setText(String.format("DPI: %d", dpi));
        } catch (NumberFormatException e) {
            dpiSlider.setValue(2);
            dpiValueText.setText(String.format("DPI: %d", 56));
        }
    }

    private void saveSettings() {
        // 保存设置到SharedPreferences
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_XUNFEI_APP_ID, xunfeiAppIdInput.getText().toString().trim());
        editor.putString(KEY_XUNFEI_API_SECRET, xunfeiApiSecretInput.getText().toString().trim());
        editor.putString(KEY_XUNFEI_API_KEY, xunfeiApiKeyInput.getText().toString().trim());
        editor.putString(KEY_DEEPSEEK_API_KEY, deepseekApiKeyInput.getText().toString().trim());
        editor.putString(KEY_DPI_STEP, String.valueOf((int)dpiSlider.getValue()));
        editor.apply();

        // 发送DPI设置命令
        int dpiStep = (int) dpiSlider.getValue();
        if (getActivity() instanceof MainActivity) {
            MainActivity activity = (MainActivity) getActivity();
            if (activity.isDeviceConnected()) {
                sendDpiCommand(dpiStep);
            } else {
                Toast.makeText(getContext(), "设备未连接,设置已保存但未发送", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void sendDpiCommand(int dpiStep) {
        if (getActivity() instanceof MainActivity) {
            MainActivity activity = (MainActivity) getActivity();
            if (activity.isDeviceConnected()) {
                // 创建命令数据包
                byte[] data = new byte[2];
                data[0] = 0x01;  // SET操作
                data[1] = (byte) dpiStep;  // DPI步进值

                // 打印完整的命令数据
                StringBuilder sb = new StringBuilder();
                for (byte b : data) {
                    sb.append(String.format("%02X ", b));
                }
                Log.i(TAG, "DPI设置命令数据: " + sb.toString());

                // 发送命令
                activity.sendCommand((byte)0x25, data);  // 0x25是ELPT_OP_MOUSE_DPI命令
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // 在Fragment暂停时保存设置
        saveSettings();
    }

    // 更新当前DPI值显示
    private void updateCurrentDpi() {
        if (getActivity() instanceof MainActivity) {
            MainActivity activity = (MainActivity) getActivity();
            if (activity.isDeviceConnected()) {
                // 从MainActivity获取当前DPI值
                int currentDpi = activity.getCurrentDpi();
                if (currentDpi > 0) {
                    currentDpiText.setText(String.format("当前DPI: %d", currentDpi));
                    // 计算对应的步进值，并确保在有效范围内
                    int dpiStep = (int) Math.round(currentDpi / 27.8);
                    if (dpiStep < 2) dpiStep = 2;
                    if (dpiStep > 116) dpiStep = 116;
                    dpiSlider.setValue(dpiStep);
                    dpiValueText.setText(String.format("DPI: %d", currentDpi));
                }
            }
        }
    }

    // 更新固件版本
    private void updateFirmwareVersion() {
        if (getActivity() instanceof MainActivity) {
            MainActivity activity = (MainActivity) getActivity();
            if (activity.isDeviceConnected()) {
                // 从MainActivity获取版本信息
                String versionText = activity.getVersionInfo();
                if (versionText != null && !versionText.equals("版本: --")) {
                    firmwareVersionText.setText(versionText);
                } else {
                    firmwareVersionText.setText("版本: --");
                }
            } else {
                firmwareVersionText.setText("版本: --");
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // 在Fragment恢复时更新固件版本
        updateFirmwareVersion();
    }

} 